package com.example.demo.msg.ali.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAppMiniTemplatemessageSendRequest;
import com.alipay.api.response.AlipayOpenAppMiniTemplatemessageSendResponse;
import com.example.demo.msg.ali.entity.AliTemplateMsg;
import com.example.demo.msg.ali.service.IAliTemplateService;
import com.google.gson.Gson;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * Created at 2021/3/7 7:56 上午
 *
 * @author Alex
 * description
 */
@Slf4j
@Service
public class AliTemplateServiceImpl implements IAliTemplateService {

    @Autowired
    private DefaultAlipayClient alipayClient;

    @Autowired
    private Gson gson;

    @Override
    public boolean sendTemplate(String userId, String formId,String templateId, String page,Map<String, String> params) {
        AlipayOpenAppMiniTemplatemessageSendRequest request = new AlipayOpenAppMiniTemplatemessageSendRequest();
        AliTemplateMsg aliTemplateMsg=new AliTemplateMsg();
        aliTemplateMsg.setTo_user_id(userId);
        aliTemplateMsg.setForm_id(formId);
        aliTemplateMsg.setPage(page);
        aliTemplateMsg.setUser_template_id(templateId);
        aliTemplateMsg.setData(gson.toJson(params));
        request.setBizContent(gson.toJson(aliTemplateMsg));
        AlipayOpenAppMiniTemplatemessageSendResponse response = null;
        try {
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("调用成功");
                return true;
            } else {
                System.out.println("调用失败");
                return false;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }

    }
}
